<?php
/**
 * Cms_Catalog
 * 
 * @category   Cms
 * @package    Cms_Model
 */
class Cms_Model_Catalog extends BIS_Model_Abstract
{    
    /**
     * Get categories by Parent Id
     *
     * @param int $parentID The parentId
     * @return Zend_Db_Table_Rowset
     */
    public function getCategoriesByParentId($parentID)
    {
        $parentID = (int) $parentID;
        
        return $this->getResource('Category')->getCategoriesByParentId($parentID);
    }
    
    /**
     * Get a category by its id
     *
     * @param  int $id The id
     * @return Cms_Resource_Category_Item|null
     */
    public function getCategoryById($id)
    {
        $id = (int) $id;

        return $this->getResource('Category')->getCategoryById($id);
    }


    /**
     * Get categories
     *
     * @param bool $withParentNamePath Prepends the parent(s) name to the Category name
     * @return Zend_Db_Table_Rowset|array Return array if $withParentNamePath is true - otherwise Zend_Db_Table_Rowset
     */
    public function getCategories($withParentNamePath = true) {
        
        $categories = $this->getResource('Category')->getCategories();

        if($withParentNamePath){

            $categoryData = array();
                
            foreach ($categories as $category) {

                $categoryData[] = array(
					'categoryId' => $category->categoryId,
					'name'        => ucwords($this->getCategoryPath($category->categoryId)),
					'parentId'  	  => $category->parentId,
					'description'  => $category->description
				);

            }
               
            // check if is an array and the row(s) is set - for sorting
            if((is_array($categoryData)) && (count($categoryData) > 0)){

                // Obtain a list of columns
                    foreach ($categoryData as $key => $row) {
                        $name[$key]  = $row['name'];
                    }

                    // Sort the data with name ascending
                    // Add $categoryData as the last parameter, to sort by the common key
                    array_multisort($name, SORT_ASC, $categoryData);
            }

            return $categoryData;

        }  else {
            return $categories;
        }
        
    }

    public function getCategoryPath($categoryId) {

		$categoryInfo = $this->getCategoryById($categoryId);

		if ($categoryInfo->parentId && $this->getCategoryById($categoryInfo->parentId)) {
			return $this->getCategoryPath($categoryInfo->parentId) . ' > ' . $categoryInfo->name;
		} else {
			return $categoryInfo->name;
		}
	}

    /**
     * Get a categories children categoryId values
     *
     * @param int     $categoryId The category to get children from
     * @param boolean $recursive  Get the entire category branch?
     * @return array An array of ids
     */
    public function getCategoryChildrenIds($categoryId, $recursive = false)
    {
        $categories = $this->getCategoriesByParentId($categoryId);
        $cats = array();

        foreach ($categories as $category) {
            $cats[] = $category->categoryId;

            if (true === $recursive) {
                $cats = array_merge($cats, $this->getCategoryChildrenIds($category->categoryId, true));
            }
        }

        return $cats;
    }

    /**
     * Save a category
     *
     * @param array  $data The data to insert/update
     * @param Zend_DB_Table_Row $row Optional The row to use
     * @return mixed The primary key
     */
    public function saveCategory($data, $row = null)
    {
        return $this->getResource('Category')->saveRow($data, $row);
    }

    /**
     * Delete a category
     *
     * @param Zend_DB_Table_Row $row The row to use
     * @return int The number of rows deleted
     */
    public function deleteCategory($row)
    {
        return $this->getResource('Category')->deleteRow($row);
    }

    /**
     * Get a product by its id
     *
     * @param  int $id The id
     * @return Cms_Resource_Product_Item|null
     */
    public function getProductById($id)
    {
        $id = (int) $id;
        
        return $this->getResource('Product')->getProductById($id);
    }
    
    /**
     * Get products in a category
     *
     * @param int         $category The category id
     * @param array|null       $data  sort, order, page, limit, search
     * @param boolean     $deep     Get all products below this category?
     * @return Zend_Db_Table_Rowset|Zend_Paginator
     */
    public function getProductsByCategory($category, $data=null, $deep=true)
    {
        $categoryId = $category;
        
        if (true === $deep) {
            $ids = $this->getCategoryChildrenIds($categoryId, true);
            $ids[] = $categoryId;
            $categoryId = null === $ids ? $categoryId : $ids;
        }

        if ($data) {

			$sortData = array('name','category');

                        $order = '';
			if (isset($data['sort']) && in_array($data['sort'], $sortData)) {
				$order .= $data['sort'];
			} else {
				$order .= "name";
			}

			if (isset($data['order']) && ($data['order'] == 'desc')) {
				$order .= " DESC";
			} else {
				$order .= " ASC";
			}

                        $data['order'] = $order;

			if (isset($data['page'])) {
				if ($data['page'] < 0) {
					$data['page'] = 0;
				}
			}

                        if (isset($data['limit'])) {
				if ($data['limit'] < 1) {
					$data['limit'] = 20;
				}
			}else{
                            $data['limit'] = 20;
                        }

			return $this->getResource('Product')->getProductsByCategory($categoryId, $data);

		} else {
			return $this->getResource('Product')->getProductsByCategory($categoryId);
			}
    }

    /**
     * Save a Product
     *
     * @param array  $data The data to insert/update
     * @param Zend_DB_Table_Row $row Optional The row to use
     * @return mixed The primary key
     */
    public function saveProduct($data, $row = null)
    {
        return $this->getResource('Product')->saveRow($data, $row);
    }

    /**
     * Delete a Product
     *
     * @param Zend_DB_Table_Row $row The row to use
     * @return int The number of rows deleted
     */
    public function deleteProduct($row)
    {
        return $this->getResource('Product')->deleteRow($row);
    }
    
    /**
     * Get All the Suppliers
     *
     * @param array|null  $data  sort, order, page, limit
     * @return Zend_Db_Table_Rowset|Zend_Paginator
     */
    public function getSuppliers($data=null)
    {
        if ($data) {

			$sortData = array('name');

                        $order = '';
			if (isset($data['sort']) && in_array($data['sort'], $sortData)) {
				$order .= $data['sort'];
			} else {
				$order .= "name";
			}

			if (isset($data['order']) && ($data['order'] == 'desc')) {
				$order .= " DESC";
			} else {
				$order .= " ASC";
			}

                        $data['order'] = $order;

			if (isset($data['page'])) {
				if ($data['page'] < 0) {
					$data['page'] = 0;
				}
			}

                        if (isset($data['limit'])) {
				if ($data['limit'] < 1) {
					$data['limit'] = 20;
				}
			}else{
                            $data['limit'] = 20;
                        }
                        
			return $this->getResource('Supplier')->getSuppliers($data);

		} else {
			return $this->getResource('Supplier')->getSuppliers();
			}
        
    }

    /**
     * Get a Supplier by its id
     *
     * @param  int $id The id
     * @return Cms_Resource_Supplier_Item|null
     */
    public function getSupplierById($id)
    {
        $id = (int) $id;

        return $this->getResource('Supplier')->getSupplierById($id);
    }

    /**
     * Save a Supplier
     *
     * @param array  $data The data to insert/update
     * @param Zend_DB_Table_Row $row Optional The row to use
     * @return mixed The primary key
     */
    public function saveSupplier($data, $row = null)
    {
        return $this->getResource('Supplier')->saveRow($data, $row);
    }

    /**
     * Delete a Supplier
     *
     * @param Zend_DB_Table_Row $row The row to use
     * @return int The number of rows deleted
     */
    public function deleteSupplier($row)
    {
        return $this->getResource('Supplier')->deleteRow($row);
    }
    
    
    /**
     * Get all assets
     *
     * @param array|null  $data  sort, order, page, limit
     * @return Zend_Db_Table_Rowset|Zend_Paginator
     */
    public function getAssets($data=null)
    {
    	if ($data) {
    
    		$sortData = array('name', 'cost');
    
    		$order = '';
    		if (isset($data['sort']) && in_array($data['sort'], $sortData)) {
    			$order .= $data['sort'];
    		} else {
    			$order .= "name";
    		}
    
    		if (isset($data['order']) && ($data['order'] == 'desc')) {
    			$order .= " DESC";
    		} else {
    			$order .= " ASC";
    		}
    
    		$data['order'] = $order;
    
    		if (isset($data['page'])) {
    			if ($data['page'] < 0) {
    				$data['page'] = 0;
    			}
    		}
    
    		if (isset($data['limit'])) {
    			if ($data['limit'] < 1) {
    				$data['limit'] = 20;
    			}
    		}else{
    			$data['limit'] = 20;
    		}
    
    		return $this->getResource('Asset')->getAssets($data);
    
    	} else {
    		return $this->getResource('Asset')->getAssets();
    	}
    
    }
    
    /**
     * Get asset by its id
     *
     * @param  int $id The id
     * @return Cms_Resource_Asset_Item|null
     */
    public function getAssetById($id)
    {
    	$id = (int) $id;
    
    	return $this->getResource('Asset')->getAssetById($id);
    }
    
    /**
     * Save an asset
     *
     * @param array  $data The data to insert/update
     * @param string $savedBy The full name of the administrator that saved or updated the data
     * @param Zend_DB_Table_Row $row Optional The row to use
     * @return mixed The primary key
     */
    public function saveAsset($data, $savedBy, $row = null)
    {
    	$currentTime = date('Y-m-d H:i:s');
    	
    	// convert purchasedDate to mysql data type
    	if (array_key_exists('purchasedDate', $data) && '' != $data['purchasedDate']) {
    		$mysqlDate = new Zend_Date($data['purchasedDate'], 'dd.MM.yyyy');
    		$data['purchasedDate'] = $mysqlDate->toString('yyyy-MM-dd');
    	}
    	
    	if(null !== $row){
    		$data['lastUpdatedBy'] = $savedBy;
    		$data['lastUpdatedDate'] = $currentTime;
    	}else{
    		$data['addedBy'] = $savedBy;
    		$data['addedDate'] = $currentTime;
    	}
    	
    	return $this->getResource('Asset')->saveRow($data, $row);
    }
    
    /**
     * Delete an asset
     *
     * @param Zend_DB_Table_Row $row The row to use
     * @return int The number of rows deleted
     */
    public function deleteAsset($row)
    {
    	return $this->getResource('Asset')->deleteRow($row);
    }
    
    /**
     * Get asset report
     *
     * @param string|null   $fromDate	From purchase date
     * @param string|null   $toDate     To purchase date
     * @return Zend_Db_Table_Rowset
     */
    public function getAssetReport($fromDate=null, $toDate=null){
    
    	return $this->getResource('Asset')->getAssetReport($fromDate, $toDate);
    
    }
   
}